<?php
declare (strict_types=1);

namespace app;

use app\model\system\SystemLog;
use think\App;
use think\Db;
use think\exception\ValidateException;
use think\Validate;

/**
 * 控制器基础类
 */
abstract class BaseController
{
    /**
     * Request实例
     * @var \think\Request
     */
    protected $request;

    /**
     * 应用实例
     * @var \think\App
     */
    protected $app;

    /**
     * 是否批量验证
     * @var bool
     */
    protected $batchValidate = false;

    /**
     * 控制器中间件
     * @var array
     */
    protected $middleware = [];

    /**
     * 构造方法
     * @access public
     * @param App $app 应用对象
     */
    public function __construct(App $app)
    {
        $this->app = $app;
        $this->request = $this->app->request;

        // 控制器初始化
        $this->initialize();
        //写入日志
        $this->saveLog();
    }

    public function saveLog()
    {
        $rule = $this->request->rule();
        $params = [
            'admin_id' => $this->request->userInfo['id'] ?? 0,
            'admin_name' => $this->request->userInfo['name'] ?? '',
            'params' => json_encode($this->request->param()),
            'name' => $rule->getName(),
            'rules' => $rule->getRule(),
            'route' => $rule->getRoute(),
            'method' => $rule->getMethod(),
            'source' => $this->request->header('source', ''),
            'ip' => getClientIp()
        ];
        (new SystemLog)->save($params);
    }

    // 初始化
    protected function initialize()
    {
        $source = $this->request->header('source', '');
        if ($source != 'web') {
            //错误
            returnMsg('必传参数错误');
        }
    }

    /**
     * 验证必传参数--获取全部参数
     * @param array $field 需要验证的字段
     * @param array $param 需要验证数组
     * @param bool $isTotal 是否需要全部参数
     * @return array|mixed
     * 调用示例   $this->checkParam(['username','password'],['username'=>"1111111",'password'=>"123123213"])
     */
    public function checkParam(array $field = [], bool $isTotal = true, array $param = [])
    {
        if (empty($param)) {
            $param = $this->request->param();
        }
        $data = [];
        foreach ($field as $v) {
            //拆分$v
            $fieldArray = explode('|', $v);
            $fields = $fieldArray[0];

            //判断是否必传参数  是否存在或者为空
            if (!isset($param[$fields])) {
                //上线请隐藏
                throw new \Exception('缺少必传参数:' . $fields);
            }
            //验证规则
            if (count($fieldArray) > 1) {
                unset($fieldArray[0]);
                foreach ($fieldArray as $vs) {
                    $this->checkRule($vs, $param[$fields]);
                }
            }
            $data[$fields] = $param[$fields];
        }
        if ($isTotal) {
            return $param;
        }
        return $data;
    }

    /**
     * 验证字段规则
     * @param $type 类型
     * @param $field  验证的字段
     * @return bool
     * @throws \Exception
     */
    public function checkRule(string $type, $field)
    {
        //验证各种骚东西 ,格式 字段名| 类型  自己写规则. 想怎么玩就怎么玩
        switch ($type) {
            case 'phone': //验证手机号
                $preg_mobile = '/^1[3456789]\d{9}$/ims';
                if (!preg_match($preg_mobile, $field)) {
                    throw new \Exception('电话号码格式错误', -1);
                }
                break;
            case 'url' :
                $preg = "/^http(s)?:\\/\\/.+/";
                if (!preg_match($preg, $field)) {
                    throw new \Exception('请输入正确的url', -1);
                }
                break;
            case 'mail':
                $pattern = "/([a-z0-9]*[-_.]?[a-z0-9]+)*@([a-z0-9]*[-_]?[a-z0-9]+)+[.][a-z]{2,3}([.][a-z]{2})?/i";
                if (!preg_match($pattern, $field)) {
                    throw new \Exception('邮箱格式错误', -1);
                }
                break;
            default:
                break;
        }
        return true;

    }

    /**
     * 验证数据
     * @access protected
     * @param array $data 数据
     * @param string|array $validate 验证器名或者验证规则数组
     * @param array $message 提示信息
     * @param bool $batch 是否批量验证
     * @return array|string|true
     * @throws ValidateException
     */
    protected function validate(array $data, $validate, array $message = [], bool $batch = false)
    {
        if (is_array($validate)) {
            $v = new Validate();
            $v->rule($validate);
        } else {
            if (strpos($validate, '.')) {
                // 支持场景
                [$validate, $scene] = explode('.', $validate);
            }
            $class = false !== strpos($validate, '\\') ? $validate : $this->app->parseClass('validate', $validate);
            $v = new $class();
            if (!empty($scene)) {
                $v->scene($scene);
            }
        }

        $v->message($message);

        // 是否批量验证
        if ($batch || $this->batchValidate) {
            $v->batch(true);
        }

        return $v->failException(true)->check($data);
    }

}
